package connections;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

public class SocketDanoConnection extends Connection {

	// public SocketDanoConnection(String _ip, int _port){
	// address = "socket://" + _ip + ":" + _port;
	// }
	ConnectorThread t;

	public SocketDanoConnection(String _ip, int _port) {
		address = "socket://" + _ip + ":" + _port;
		mainProgram = this;
		t = new ConnectorThread();
		t.start();
	}

	public SocketDanoConnection(String _ip, int _port, ConnectionListener _cl) {
		// pass the listener right away so it lets you know right away about the conection
		address = "socket://" + _ip + ":" + _port;
		mainProgram = _cl;
		if (_cl == null) mainProgram = this;
		t = new ConnectorThread();
		t.start();
	}

	public void finishedConnection(boolean _good) {
		if (_good) {

			mainProgram.connectionMade(this, address);
		} else {
			mainProgram.feedback(this, "Server Not Responding");
			mainProgram = null;
		}

	}
	public String getAddress() {
		String wholeAddress = super.getAddress();
		
		wholeAddress = wholeAddress.replace(':',' ');

		return wholeAddress.substring(9);
	}

	class ConnectorThread extends Thread {
		public void run() {
			try {
				SocketConnection socket = (SocketConnection) Connector.open(address);
				is = socket.openInputStream();
				os = socket.openOutputStream();
				finishedConnection(true);
			} catch (Exception e) {
				finishedConnection(false);

			}
		}

	}

}
